using System;
using Microsoft.SPOT;

namespace PeteBrown.MidiUtilities
{
    public class MidiUtility
    {
        public const byte MiddleCNoteNumber = 60;
        public const byte A440NoteNumber = 69;

        public const int MinimumOctave = -1;
        public const int MaximumOctave = 9;

        public const byte MinimumNoteNumber = 0;
        public const byte MaximumNoteNumber = 127;

        // I use the standard of -1 to 9 for octave numbers. There are other
        // standards out there.
        public static byte NoteNameToMidiNoteNumber(MusicalNote note, int octave)
        {
            if (octave < MinimumOctave || octave > MaximumOctave)
                throw new ArgumentException("Octave must be between " + MinimumOctave + " and " + MaximumOctave + ".", "octave");

            return (byte)((octave + 1) * 12 + (byte)note);

        }

        // this won't distinguish between sharps/flats as they have the same value
        // so the note you get back will be the correct number, but may not fit
        // the conventions for whatever key you're in
        public static MusicalNote MidiNoteNumberToNameAndOctave(byte midiNoteNumber, out int octave)
        {
            if (midiNoteNumber < MinimumNoteNumber || midiNoteNumber > MaximumNoteNumber)
                throw new ArgumentException("Note must be between " + MinimumNoteNumber + " and " + MaximumNoteNumber + ".", "midiNoteNumber");

            octave = midiNoteNumber / 12 - 1;

            return (MusicalNote)(midiNoteNumber % 12);
        }



        //#if USE_NOTE_FREQUENCY_TABLE
        //        private float[] _noteFrequencies = new float[]
        //        {

        //        };
        //#endif

        //        // frequency in Hertz
        //        // given the math and that this will run on microcontrollers, it's really 
        //        // best accomplished with a lookup table for speed.
        //        public static float MidiNoteNumberToFrequency(byte midiNoteNumber)
        //        {
        //#if USE_NOTE_FREQUENCY_TABLE
        //#else
        //#endif
        //        }

    }
}
